package com.soywer.rpc.future;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;


/**
 * 功能描述：
 *
 * @Author: limeng54
 * @Date: 2021/4/2 15:06
 */
public class FutureDemo3 {
    private static ExecutorService executor = Executors.newFixedThreadPool(4);

    public static void main(String[] args) throws InterruptedException, ExecutionException {

//        //方法一
//        long start = System.currentTimeMillis();
//
//        Future<String> f1 = executor.submit(new MyCallable("包子",1));
//        Future<String> f2 = executor.submit(new MyCallable("黄瓜",2));
//        Future<String> f3 = executor.submit(new MyCallable("牛肉",3));
//
//
//        System.out.println("包子是否完成:"+f1.isDone());
//        System.out.println("黄瓜是否完成:"+f2.isDone());
//        System.out.println("牛肉是否完成:"+f3.isDone());
//
//        System.out.println(f1.get());
//        System.out.println(f2.get());
//        System.out.println(f3.get());
//
//        System.out.println("包子是否完成:"+f1.isDone());
//        System.out.println("黄瓜是否完成:"+f2.isDone());
//        System.out.println("牛肉是否完成:"+f3.isDone());
//
//        long end = System.currentTimeMillis();
//        System.out.println("准备完毕时间："+(end-start));
//        System.out.println(executor.isShutdown());
//        executor.shutdown();
//        System.out.println(executor.isShutdown());


        //方法二

        long start2 = System.currentTimeMillis();
        List<Callable<String>> tasks = new ArrayList<>();
        MyCallable m1 = new MyCallable("包子",1);
        MyCallable m2 = new MyCallable("黄瓜",2);
        MyCallable m3 = new MyCallable("牛肉",3);
        tasks.add(m1);
        tasks.add(m2);
        tasks.add(m3);

        List<Future<String>> futureList = executor.invokeAll(tasks);
        for (Future<String> stringFuture : futureList) {
            System.out.println(stringFuture.get());
        }
        executor.shutdown();
        long end2 = System.currentTimeMillis();
        System.out.println("准备完毕时间："+(end2-start2));
    }


    static class MyCallable implements Callable<String> {

        private String menuName;
        private Integer delayMinute;

        public MyCallable(String menuName,Integer delayMinute) {
            this.menuName = menuName;
            this.delayMinute = delayMinute;
        }

        @Override
        public String call() throws Exception {

            try {
                Thread.sleep(1000*this.delayMinute);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return this.menuName + "准备完毕";
        }
    }


}
